
#include "../gpio/sysfs_gpio.h"
#include <fcntl.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define PWM_PATH "/sys/class/pwm/pwmchip0"


// 导出 PWM 通道
int pwm_export(int channel) {
    FILE *pwm_export = fopen(PWM_PATH "/export", "w");
    if (!pwm_export) {
        perror("Failed to open PWM export");
        return 1;
    }
    fprintf(pwm_export, "%d", channel);
    fclose(pwm_export);
    return 0;
}

// 取消导出 PWM 通道
int pwm_unexport(int channel) {
    FILE *pwm_unexport = fopen(PWM_PATH "/unexport", "w");
    if (!pwm_unexport) {
        perror("Failed to open PWM unexport");
        return 1;
    }
    fprintf(pwm_unexport, "%d", channel);
    fclose(pwm_unexport);
    return 0;
}

// 设置 PWM 周期
int pwm_set_period(int channel, int period_ns) {
    char period_path[128];
    snprintf(period_path, sizeof(period_path), PWM_PATH "/pwm%d/period", channel);

    FILE *period_file = fopen(period_path, "w");
    if (!period_file) {
        perror("Failed to open PWM period");
        return 1;
    }
    fprintf(period_file, "%d", period_ns);
    fclose(period_file);
    return 0;
}

// 设置占空比
int pwm_set_duty_cycle(int channel, int duty_cycle_ns) {
    char duty_cycle_path[128];
    snprintf(duty_cycle_path, sizeof(duty_cycle_path), PWM_PATH "/pwm%d/duty_cycle", channel);

    FILE *duty_cycle_file = fopen(duty_cycle_path, "w");
    if (!duty_cycle_file) {
        perror("Failed to open PWM duty cycle");
        return 1;
    }
    fprintf(duty_cycle_file, "%d", duty_cycle_ns);
    fclose(duty_cycle_file);
    return 0;
}

// 启用/禁用 PWM
int pwm_enable(int channel, int enable) {
    char enable_path[128];
    snprintf(enable_path, sizeof(enable_path), PWM_PATH "/pwm%d/enable", channel);

    FILE *enable_file = fopen(enable_path, "w");
    if (!enable_file) {
        perror("Failed to open PWM enable");
        return 1;
    }
    fprintf(enable_file, "%d", enable);
    fclose(enable_file);
    return 0;
}